package com.example.fszq.volleydemo1;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.fszq.volleydemo1.adapters.ImageSelectAdapter;
import com.example.fszq.volleydemo1.layout.ListImageDirPopupWindow;
import com.example.fszq.volleydemo1.thread.ImagePocCallBack;
import com.example.fszq.volleydemo1.thread.ImagePocThread;
import com.example.fszq.volleydemo1.utils.ImageFolder;
import com.example.fszq.volleydemo1.thread.UploadImageThread;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class ImageSelectorActivity extends Activity  {
    private ProgressDialog mProgressDialog;

    /**
     * 存储文件夹中的图片数量
     */
    private int mPicsSize;
    /**
     * 图片数量最多的文件夹
     */
    private File mImgDir;
    /**
     * 所有的图片
     */
    private List<String> mImgs;
    /**
     * 临时的辅助类，用于防止同一个文件夹的多次扫描
     */
    private HashSet<String> mDirPaths = new HashSet<String>();
    /**
     * 扫描拿到所有的图片文件夹
     */
    private List<ImageFolder> mImageFloders = new ArrayList<ImageFolder>();
    private ImageSelectAdapter mAdapter;

    /**
     * 用户选择的图片，存储为图片的完整路径
     */
//    public static ArrayList<String> mSelectedImage = new ArrayList<String>();
    public  ArrayList<String> mSelectedImage = new ArrayList<String>();

    /** 选择结果，返回为 ArrayList&lt;String&gt; 图片路径集合  */
    public static final String EXTRA_RESULT = "select_result";
    /**
     * 文件夹路径
     */
    private String mDirPath;

    //popup window对象
    private ListImageDirPopupWindow mListImageDirPopupWindow;

    /*---- 图片处理相关,线程池相关 start-----*/

    private List<UploadImageThread> mTaskList = null;

    private static final int tcount = 5; //最大5张图片
    private int i = 0;

    private static ExecutorService sTaskExe = null;
    static {
        sTaskExe = Executors.newSingleThreadExecutor();// 每次只执行一个线程任务的线程池
    }
    /** 任务是否被取消 */
    private boolean isCancled = false;

    UploadImageThread task ;
    /*------图片处理相关,线程池相关 end -------*/

    private ImagePocCallBack ipc;
    private GridView mGirdView;
    private TextView mImageCount,mChoseDir;
    private ImageView sImage,sItemSelected;
    private Button mCommit;

    private RelativeLayout id_bottom_ly;

    private int mScreenHeight;
    int totalCount = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_selector);

        DisplayMetrics outMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        mScreenHeight = outMetrics.heightPixels;

        //initview
        mGirdView = (GridView) findViewById(R.id.id_gridView);
        mImageCount = (TextView)findViewById(R.id.id_total_count);

        mCommit = (Button)findViewById(R.id.commit);
        mCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mSelectedImage.isEmpty() == false && mSelectedImage.size() > 0) {
                    //进行图片压缩处理操作
                    //mProgressDialog = ProgressDialog.show(ImageSelectorActivity.this, null, "图片处理中...");
                    ImagePocThread ipt;
                    ipt = new ImagePocThread(ImageSelectorActivity.this, mSelectedImage, new ImagePocCallBack() {
                        @Override
                        public void CompressOk(ArrayList<String> cPath) {
                            // 返回已选择的图片数据
                            Log.d("mSelectedImage.size()", cPath.size() + "");
                            Intent data = new Intent();
                            data.putStringArrayListExtra(EXTRA_RESULT, cPath);

                            setResult(RESULT_OK, data);
                            finish();
                        }
                    });
                    ipt.execute();


                    //ipt.setAfterListener(new ImagePocThread.AfterLoad() {
                    //    @Override
                    //    public void onAfterLoad(Bitmap bitmap, int position) {

                    //    }
                    //});
                }
            }
        });


        getImages();

        mChoseDir = (TextView)findViewById(R.id.id_choose_dir);
        id_bottom_ly = (RelativeLayout)findViewById(R.id.id_bottom_ly);
        initEvent();
    }


    private Handler mHandler = new Handler()
    {
        public void handleMessage(android.os.Message msg)
        {
            mProgressDialog.dismiss();
            // 为View绑定数据
            data2View();
            // 初始化展示文件夹的popupWindw
            initListDirPopupWindw();

        }
    };

    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED))
        {
            Toast.makeText(this, "暂无外部存储", Toast.LENGTH_SHORT).show();
            return;
        }

        // 显示进度条
        mProgressDialog = ProgressDialog.show(this, null, "正在加载...");

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {

                String firstImage = null;

                Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                ContentResolver mContentResolver = ImageSelectorActivity.this
                        .getContentResolver();

                // 只查询jpeg和png的图片
                Cursor mCursor = mContentResolver.query(mImageUri, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or "
                                + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[] { "image/jpeg", "image/png" },
                        MediaStore.Images.Media.DATE_MODIFIED);

                Log.e("TAG", mCursor.getCount() + "");
                while (mCursor.moveToNext())
                {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor
                            .getColumnIndex(MediaStore.Images.Media.DATA));

                    Log.e("TAG", path);
                    // 拿到第一张图片的路径
                    if (firstImage == null)
                        firstImage = path;
                    // 获取该图片的父路径名
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    ImageFolder imageFloder = null;
                    // 利用一个HashSet防止多次扫描同一个文件夹（不加这个判断，图片多起来还是相当恐怖的~~）
                    if (mDirPaths.contains(dirPath))
                    {
                        continue;
                    } else
                    {
                        mDirPaths.add(dirPath);
                        // 初始化imageFloder
                        imageFloder = new ImageFolder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }

                    int picSize = parentFile.list(new FilenameFilter()
                    {
                        @Override
                        public boolean accept(File dir, String filename)
                        {
                            if (filename.endsWith(".jpg")
                                    || filename.endsWith(".png")
                                    || filename.endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    }).length;
                    totalCount += picSize;

                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);

                    if (picSize > mPicsSize)
                    {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();

                // 扫描完成，辅助的HashSet也就可以释放内存了
                mDirPaths = null;

                // 通知Handler扫描图片完成
                mHandler.sendEmptyMessage(0x110);

            }
        }).start();
    }

    /**
     * 为View绑定数据
     */
    private void data2View()
    {
        if (mImgDir == null)
        {
            Toast.makeText(getApplicationContext(), "一张图片没扫描到",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        mImgs = Arrays.asList(mImgDir.list());
        /**
         * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
         */
        mAdapter = new ImageSelectAdapter(ImageSelectorActivity.this,R.layout.image_select_grid_item,mImgs,mImgDir.getAbsolutePath());
        mGirdView.setAdapter(mAdapter);
        mGirdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Log.d("vvvvv",position+"");
                mDirPath = mImgDir.getAbsolutePath();
                String imgSrc = mImgs.get(position);
                sImage = (ImageView)view.findViewById(R.id.id_item_image);
                sItemSelected = (ImageView)view.findViewById(R.id.id_item_select);
                if (mSelectedImage.contains(mDirPath + "/" + imgSrc)) {
                    //Log.d("clickimage1", mDirPath + "/" + imgSrc);
                    mSelectedImage.remove(mDirPath + "/" + imgSrc);
                    sItemSelected.setImageResource(R.drawable.picture_unselected);
                    sImage.setColorFilter(null);
                } else {
                    //Log.d("clickimage2", mDirPath + "/" + imgSrc);
                    mSelectedImage.add(mDirPath + "/" + imgSrc);
                    sItemSelected.setImageResource(R.drawable.pictures_selected);
                    sImage.setColorFilter(Color.parseColor("#77000000"));
                }

                if(mSelectedImage.contains(mDirPath + "/" + imgSrc)) {
                    sItemSelected.setImageResource(R.drawable.pictures_selected);
                    sImage.setColorFilter(Color.parseColor("#77000000"));
                };
            }
        });

        mImageCount.setText(totalCount + "张");
    };

    private void initEvent()
    {
        /**
         * 为底部的布局设置点击事件，弹出popupWindow
         */
        mChoseDir.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mListImageDirPopupWindow
                        .setAnimationStyle(R.style.anim_popup_dir);
                mListImageDirPopupWindow.showAsDropDown(id_bottom_ly, 0, 0);

                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = .3f;
                getWindow().setAttributes(lp);
            }
        });
    }

    /**
     * 初始化展示文件夹的popupWindw
     */
    private void initListDirPopupWindw()
    {
        //Log.d("dircount",mImageFloders.size()+"");
        //Toast.makeText(this, mImageFloders.size()+"", Toast.LENGTH_SHORT).show();

        mListImageDirPopupWindow = new ListImageDirPopupWindow(
                ViewGroup.LayoutParams.MATCH_PARENT, (int) (mScreenHeight * 0.7),
                mImageFloders, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.selectattach_dirlist, null));

        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                // 设置背景颜色变暗
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        // 设置选择文件夹的回调
        mListImageDirPopupWindow.setOnImageDirSelected(new ListImageDirPopupWindow.OnImageDirSelected() {
            @Override
            public void selected(ImageFolder floder) {
                mImgDir = new File(floder.getDir());
                mImgs = Arrays.asList(mImgDir.list(new FilenameFilter()
                {
                    @Override
                    public boolean accept(File dir, String filename)
                    {
                        if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                || filename.endsWith(".jpeg"))
                            return true;
                        return false;
                    }
                }));

                /**
                 * 可以看到文件夹的路径和图片的路径分开保存，极大的减少了内存的消耗；
                 */
                mAdapter = new ImageSelectAdapter(ImageSelectorActivity.this,R.layout.image_select_grid_item,mImgs,mImgDir.getAbsolutePath());
                mGirdView.setAdapter(mAdapter);
                mGirdView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        //Log.d("vvvvv",position+"");
                        mDirPath = mImgDir.getAbsolutePath();
                        String imgSrc = mImgs.get(position);
                        sImage = (ImageView)view.findViewById(R.id.id_item_image);
                        sItemSelected = (ImageView)view.findViewById(R.id.id_item_select);
                        if (mSelectedImage.contains(mDirPath + "/" + imgSrc)) {
                            //Log.d("clickimage1", mDirPath + "/" + imgSrc);
                            mSelectedImage.remove(mDirPath + "/" + imgSrc);
                            sItemSelected.setImageResource(R.drawable.picture_unselected);
                            sImage.setColorFilter(null);
                        } else {
                            //Log.d("clickimage2", mDirPath + "/" + imgSrc);
                            mSelectedImage.add(mDirPath + "/" + imgSrc);
                            sItemSelected.setImageResource(R.drawable.pictures_selected);
                            sImage.setColorFilter(Color.parseColor("#77000000"));
                        }

                        if(mSelectedImage.contains(mDirPath + "/" + imgSrc)) {
                            sItemSelected.setImageResource(R.drawable.pictures_selected);
                            sImage.setColorFilter(Color.parseColor("#77000000"));
                        };
                    }
                });

                mImageCount.setText(totalCount + "张");
                mChoseDir.setText(floder.getName());
                mListImageDirPopupWindow.dismiss();

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_image_selector, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
